<template>
  <div class="main-wrapper">
    <div class="title">空空儿</div>
    <div class="content-wrapper">
      <van-tabs v-model:active="active" @change="changeTab" type="card" color="#FFFFFF" background="#F7F7FA" swipeable>
        <van-tab title="配置" name="0">
          <div class="form-wrapper">
            <ConfigView v-if="active === '0'" />
          </div>
        </van-tab>
        <van-tab title="账号" name="1">
          <div class="form-wrapper">
            <AccountView v-if="active === '1'" />
          </div>
        </van-tab>
        <van-tab title="历史" name="2">
          <div class="form-wrapper">
            <HistoryView v-if="active === '2'" ref="historyViewRef" />
          </div>
        </van-tab>
      </van-tabs>
    </div>

    <floating-button ref="logFloatingButton" icon="description" height="80vh" @click="store.dispatch('stopLogPolling')"
      @open="fetchLogs">
      <template #popup-content>
        <div class="log-popup">
          <div class="log-header">
            <span>日志查看</span>
          </div>
          <div class="log-content">
            <van-empty v-if="!logs.length" description="暂无日志" />
            <div v-else class="log-list">
              <div v-for="(log, index) in logs" :key="index" class="log-item"
                :style="{ color: getLogType(log.log_state) }">
                <span class="log-time">{{ log.log_time }}</span>
                <span class="log-message">{{ log.log_msg }}</span>
              </div>
            </div>
          </div>
        </div>
      </template>
    </floating-button>
  </div>
</template>

<script>
import { ref, nextTick, onMounted, onUnmounted, computed, watch } from 'vue'
import { useStore } from 'vuex'
import { useRoute } from 'vue-router'
import FloatingButton from '@/components/FloatingButton.vue';
import ConfigView from '@/views/ConfigView.vue';
import AccountView from '@/views/AccountView.vue';
import HistoryView from '@/views/HistoryView.vue';
import { StorageUtil } from '@/utils/storage';
import { loginApi } from '@/api';

export default {
  components: {
    FloatingButton,
    ConfigView,
    AccountView,
    HistoryView
  },
  setup() {
    const store = useStore()
    const route = useRoute()
    const logFloatingButton = ref(null)

    const logs = computed(() => store.state.logs)
    const autoOpenLogPopup = computed(() => store.state.autoOpenLogPopup)
    const logInterval = computed(() => store.state.logInterval)

    const fetchLogs = () => {
      store.dispatch('fetchLogs')
    }

    const startLogPolling = () => {
      store.dispatch('startLogPolling')
    }

    const stopLogPolling = () => {
      store.dispatch('stopLogPolling')
    }

    const hasOpenedLogPopupFirstTime = ref(false)

    const getLogType = (logState) => {
      return logState === 1 ? '#000' : 'red'
    }

    watch(logInterval, (newValue) => {
      if (!newValue) {
        hasOpenedLogPopupFirstTime.value = false
      }
    })

    watch(autoOpenLogPopup, (newValue) => {
      console.log('日志弹窗变化：', newValue);

      if (newValue && !hasOpenedLogPopupFirstTime.value) {
        logFloatingButton.value.handleClick()
        hasOpenedLogPopupFirstTime.value = true
        store.commit('setAutoOpenLogPopup', false)
      }
    })

    const historyViewRef = ref(null)

    const changeTab = (val) => {
      console.log(val);

      store.commit('setActive', val)
    }

    onUnmounted(() => {
      stopLogPolling()
    })

    // // 统一的日志轮询处理方法
    // const handleLogPolling = (isGrabbing) => {
    //   if (isGrabbing) {
    //     // 开始全局日志轮询
    //     store.dispatch('startLogPolling')
    //   } 
    // }
    // // 在登录后处理日志轮询
    // const cardKey = StorageUtil.getCardKey();
    // loginApi.login(cardKey)
    //   .then(response => {
    //     if (response.state) {
    //       // 调用统一的日志轮询处理方法
    //       handleLogPolling(response.state)
    //     }
    //   })
    //   .catch(error => {
    //     console.error('Login failed', error)
    //   })

    return {
      historyViewRef,
      changeTab,
      logs,
      logFloatingButton,
      fetchLogs,
      startLogPolling,
      stopLogPolling,
      active: computed(() => store.state.active),
      getLogType
    }
  }
};
</script>

<style lang="less" scoped>
.main-wrapper {
  background-color: #F3F5F8;

  .title {
    font-size: 2.5rem;
    padding: 1rem;
    text-align: center;
    background-color: #fff;
    font-family: "阿里妈妈刀隶体 Regular";
  }

  .content-wrapper {
    // padding: 15px;
  }

  .form-wrapper {
    height: calc(100vh - 133px);
    overflow-y: auto;
  }
}

.content-wrapper {
  max-width: 650px;
  margin: 0 auto;

  /deep/.van-tabs__nav--card {
    margin: 0;
  }

  /deep/.van-tab--card {
    color: var(--black);
    border: 0;
  }

  /deep/.van-tab__text {
    color: #474749;
  }

  /deep/.van-tabs__nav {
    border: 0 !important;
  }

  /deep/.van-tabs__wrap {
    width: 94%;
    margin: 20px auto;
  }
}

.log-popup {
  .log-header {
    padding: 15px;
    font-weight: bold;
    text-align: center;
    border-bottom: 1px solid #eee;
  }

  .log-content {
    padding: 10px;
    max-height: 70vh;
    overflow-y: auto;
  }

  .log-list {
    .log-item {
      display: flex;
      margin-bottom: 10px;
      padding: 5px 0;
      border-bottom: 1px solid #f0f0f0;

      .log-time {
        flex: 0 0 150px;
        color: #999;
        margin-right: 10px;
      }

      .log-type {
        flex: 0 0 60px;
        text-align: center;
        border-radius: 3px;
        padding: 2px 5px;
        margin-right: 10px;

        &.log-type-info {
          background-color: #e6f7ff;
          color: #1890ff;
        }

        &.log-type-warning {
          background-color: #fffbe6;
          color: #faad14;
        }

        &.log-type-error {
          background-color: #fff2f0;
          color: #f5222d;
        }
      }

      .log-message {
        flex: 1;
      }
    }
  }
}

@font-face {
  font-family: "阿里妈妈刀隶体 Regular";font-weight: 400;src: url("//at.alicdn.com/wf/webfont/toXfpmutf52w/2TsIAsgtM8nl.woff2") format("woff2"),
  url("//at.alicdn.com/wf/webfont/toXfpmutf52w/804T1x7vxPZN.woff") format("woff");
  font-display: swap;
}
</style>
